#!/bin/bash

add(){
	clear
	echo -e "输入姓名（空格） 信息\n"
	if [ ! -f ./record ];then
		touch record
	fi	
	read NEW

#	if [ -z $NEW ];then
#		echo -e "你没输入姓名\n请2s后重新输入" ;
#		sleep 2
#		read NEW
#	fi

	echo "$NEW" >>./record
#sort -o存入目的文件
	sort  -o ./record ./record
	echo -e "\n\n--添加结束--"
	 
}


search(){
	clear
	echo "输入姓名"
	read NEW
	if [ ! -f ./record ]; then
		clear
		echo "查找失败，没有数据"
		sleep 2
		return
	fi

#if判断条件
	if [ -z $NEW ]; then
		echo "查询时未输入姓名"
		echo "2s后重新输入姓名查询"
		sleep 2
		read NEW	
	fi
	
#grep后把标准错误重定向到error里，再用 $? 判断error里的返回值
	grep -i "$NEW" ./record 2> ./error

#case的匹配是根据grep的结果，有out为1标准输出（只是为空值？），没有out为2标准错误
	case "$?" in
		1) echo "未在记录中."
		;;
		2) echo "未输入姓名查询"
		sleep 2;
		search;;
	esac
	echo -e "\n--搜索结束--"
}

delete(){
	clear
	echo "输出需要删除的姓名"
	read NEW
	if [ -z $NEW ];then
		echo -e "你没输入姓名\n请2s后重新输入" ;
		sleep 2
		read NEW
	fi
	
	if [ ! -f ./record ]; then
		echo "删除失败，记录为空"
	else
		cp record record3
#
		grep -v $NEW ./record3 > ./record
		rm -f record3		
	fi
	echo "--删除结束--"
}

show(){
	clear
	if [ ! -f ./record ]; then
		echo "展示失败，需要先导入至少一个数据"
		return
	fi 
	cat ./record
	echo "--展示结束--"
}

list(){
	clear
	if [ ! -f ./record ]; then
		echo "查询失败，需要先导入至少一个数据"
		return
	fi 
	awk '{print $1}' ./record
	echo -e "\n--列出名单结束--"
}

deleteAll(){
	clear
	rm -f ./record
	echo -e "--删除结束--"
}

quit(){
	clear
	exit
}

clear
while true
echo -e "\n\n\n"

do
	echo "-----------------------------------------"
	echo "|1-添加					|"
	echo "|2-查找					|"
	echo "|3-删除					|"
	echo "|4-展示所有数据				|"
	echo "|5-列出所有人名字			|"
	echo "|woshisb-删除全部数据			|"
	echo "|q-退出					|"
	echo "-----------------------------------------"
	read CHOICE
	
	case $CHOICE in
	1)add ;;
	2)search;;
	3)delete;;
	4)show;;
	5)list;;
	woshisb)deleteAll;;
	q)quit;;
	
	esac
done
